var express = require('express');
var router = express.Router();

// 导入db，操作数据库
const { getAll, getById, exec } = require('../db');

/**
 * 获取所有事件
 * GET /auditEvent
 */

router.get('/', async (req, res) => {
	// 解析请求参数
	// 解构query对象,提取page,size
	// 如果没有值,就给默认值1,2
	const { page = 1, size = 2 } = req.query;
	// 获取总数
	let sql = `select count(*) as total from gg_event`;
	const obj = await getById(sql); // { total: xx }

	// 根据分页公式, 计算offset偏移量
	let offset = (page - 1) * size;
	// 操作数据库
	sql = `select event_id,gg_event.user_id,gg_user.user_name,event_type,event_addr,event_mark,event_time,event_describe,event_status from gg_event LEFT JOIN gg_user on gg_event.user_id = gg_user.user_id order by event_id limit ${offset},${size}`;
	const data = await getAll(sql);
	sql = `select event_id,gg_event.user_id,gg_user.user_name,event_type,event_addr,event_mark,event_time,event_describe,event_status from gg_event LEFT JOIN gg_user on gg_event.user_id = gg_user.user_id order by event_id`;
	const dataAll = await getAll(sql);
	res.send({
		code: 0,
		message: '获取全部待审核事件成功',
		result: {
			total: obj.total,
			data: data,
			dataAll: dataAll,
		},
	});
});

/**
 * 更新状态为通过
 * PUT /auditEvent
 */

router.put('/:id', async (req, res) => {
	const { id } = req.params;
	const { event_status } = req.body;
	let sql = `update gg_event set event_status=${event_status} where event_id=${id}`;
	await exec(sql);

	res.send({
		code: 0,
		message: '更新状态成功',
		result: event_status,
	});
});

module.exports = router;
